package com.zut.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thingsboard.rest.client.RestClient;
import org.thingsboard.server.common.data.Device;
import org.thingsboard.server.common.data.id.DeviceId;
import org.thingsboard.server.common.data.security.DeviceCredentials;

import java.util.Optional;

@Service
public class ThingsBoardService {
    public final RestClient client;


    @Autowired
    public ThingsBoardService(RestClient client) {
        this.client = client;
    }

    public String getDeviceToken(String deviceName) throws Exception{
        Optional<Device> optionalDevice = client.getTenantDevice(deviceName);
        DeviceId deviceId = optionalDevice.map(Device::getId).orElse(null);
        Optional<DeviceCredentials> optionalCredentials = client.getDeviceCredentialsByDeviceId(deviceId);
        String token = optionalCredentials.map(DeviceCredentials::getCredentialsId).orElse("Not available");
        return token;
    }


    public boolean createDevice(String deviceName) throws Exception{
        Device device = new Device();
        device.setName(deviceName);
        device.setType("default");
        client.saveDevice(device);
        return true;
    }


}
